<template>
	<view>
		<view class="usermain">
			<view class="usermain-item">
				<view style="color: #FFFFFF">头像</view>
				<view @click="uploadImg()">
					<image src="../../static/logo.png" v-if="user.avr==null" mode=""
						style="width: 111rpx;height: 111rpx;border-radius: 50%;"></image>
					<image v-else :src="user.avr" mode="" style="width: 111rpx;height: 111rpx;border-radius: 50%;">
					</image>
				</view>
			</view>
			<view class="usermain-item item-padding">
				<view style="color: #FFFFFF;">账号</view>
				<view>
					<view class="cu-form-group">
						<input style="color: #FFFFFF;" v-model="user.account" placeholder="请输入账号" disabled="true" />
					</view>
				</view>
			</view>
			<view class="usermain-item item-padding">
				<view style="color: #FFFFFF;">昵称</view>
				<view>
					<view class="cu-form-group">
						<input style="color: #FFFFFF;" v-model="user.nick" placeholder="请输入昵称" />
					</view>
				</view>
			</view>
			<view class="usermain-item item-padding">
				<view style="color: #FFFFFF;">性别</view>
				<view>
					<view class="cu-form-group">
						<input style="color: #FFFFFF;" v-model="user.gender" placeholder="请选择性别" disabled="true" />
					</view>
				</view>
			</view>


			<view class="usermain-item item-padding">
				<view style="color: #FFFFFF;">生日</view>
				<view>
					<view class="cu-form-group">
						<view>
							<input style="color: #FFFFFF;float: left;" v-model="user.birthday" placeholder="请选择出生日期"
								disabled="" />
							<u-calendar v-model="show" mode="date" @change="change"></u-calendar>
							<image src="https://cdn.uviewui.com/uview/demo/calendar/7.png"
								style="height: 16px;width: 16px;" @click="show = true">
						</view>
					</view>
				</view>
			</view>
			<view class="usermain-item item-padding" style="height: 36px;">
				<view style="color: #FFFFFF;">个性签名</view>
			</view>
			<view class="usermain-item item-padding">
				<view class="cu-form-group">
					<textarea
						style="color: #FFFFFF;width: 310px;border:  1px dashed #333333;padding: 5px;margin-top: -3px;"
						cols="30" maxlength="500" rows="6" align="left" v-model="user.signature"
						placeholder="请输入您的个性签名" />
				</view>
			</view>
			<view class="usermain-item item-padding">
				<view style="color: #FFFFFF;">用户图片</view>
			</view>
			<view style="display: flex; flex-wrap: wrap; padding: 10rpx 10rpx;">
				<view v-for="(img,index) in user.userImages" v-if="user.userImages.length<=2">
					<u-image style="margin:  20rpx 20rpx;" :src="img" width="320rpx" height="320rpx" mode=""
						@click="shanchu(index)">
					</u-image>
				</view>
				<view v-for="(img,index) in user.userImages" v-if="user.userImages.length==3">
					<u-image style="margin:  20rpx 20rpx;" :src="img" width="200rpx" height="200rpx" mode=""
						@click="shanchu(index)">
					</u-image>
				</view>
				<view v-for="(img,index) in user.userImages" v-if="user.userImages.length==4">
					<u-image style="margin:  20rpx 20rpx;" :src="img" width="320rpx" height="320rpx" mode=""
						@click="shanchu(index)">
					</u-image>
				</view>
				<view v-for="(img,index) in user.userImages" v-if="user.userImages.length>4">
					<u-image style="margin:  20rpx 20rpx;" :src="img" width="200rpx" height="200rpx" mode=""
						@click="shanchu(index)">
					</u-image>
				</view>
			</view>
			<view class="example-body">
				<uni-file-picker limit="4" @select="selectFile" @delete="deleteFile" v-model="imgList">
				</uni-file-picker>
			</view>
		</view>
		<view class="footer-btn">
			<view class="usermain-btn" @click="messagebtn()">保存</view>
		</view>
	</view>
</template>

<script>
	// import configdata from '../../common/config.js';
	export default {
		data() {
			return {
				//calendar 
				show: false,
				mode: 'single',
				//calendar 
				urls: [],
				user: {
					"id": '',
					'avr': null,
					'authPw': 'n',
					"userImages": [],
				},
				formData: {
					imgSrc: [],
					introduction: "",
				},
				phone: '',
				headImg: '../../static/logo.png',
				userName: '',
				nickName: '',
				userId: '',
				realName: '',
				weChatId: "",
				password: '',
				platform: '',
				createTime: '',
				money: '',
				jiFen: '',
				status: '',
				zhiFuBao: '',
				zhiFuBaoName: '',
				imgList: [],
			};
		},
		onLoad(options) {
			// this.getUserInfo()

			console.log(options.id);
			//（1）获取跳转过来传过来的用户id
			this.user.id = options.id;
			//（2）根据id把用户的个人信息查询展示出来
			console.log(this.user);
			this.$myRequest({
				url: "/user/byId",
				method: "get",
				data: {
					"id": this.user.id
				}
			}).then(r => {

				console.log(r)
				if (r.data.code == "200") {
					this.user = r.data.data;
					this.urls = r.data.data.userImages;
				} else {
					uni.showToast({
						title: "系统繁忙",
						//将值设置为 success 或者直接不用写icon这个参数
						icon: 'fail',
						//显示持续时间为 2秒
						duration: 2000
					})
				}
				console.log(this.user);
			})
		},
		methods: {
			shanchu(index) {
				console.log(this.user.userImages[index]);
				let url = this.user.userImages[index]
				let that = this;
				uni.showModal({
					title: '删除',
					content: '请问要删除改图片吗吗？',
					success: function(res) {
						if (res.confirm) {
							that.$myRequest({
								url: "/delete/image/",
								data:{
									url
								},
								method: "get",
							}).then(r=>{
								if(r.data.code == 200){
									that.user.userImages.splice(index, 1);
								}
							})
						} else if (res.cancel) {
							console.log('用户点击取消')
						}
					}
				});
			},
			//calendar日历，回调函数，获取选择的日期
			change(e) {
				console.log(e);
				this.user.birthday = e.result;
			},
			goMyAddress() {
				uni.navigateTo({
					url: '../jifen/myaddress'
				});
			},
			uploadImg() {
				// let token = this.$queue.getData('token');
				// if (!token) {
				// 	this.goLoginInfo();
				// 	return;
				// }
				let that = this;
				var url = null;
				uni.showActionSheet({
					// itemList按钮的文字接受的是数组
					itemList: ["查看头像", "从相册选择图片"],
					success(e) {
						var index = e.tapIndex
						if (index === 0) {
							// 用户点击了预览当前图片
							// 可以自己实现当前头像链接的读取
							let url = that.user.avr;
							let arr = []
							arr.push(url)
							uni.previewImage({
								// 预览功能图片也必须是数组的
								urls: arr
							})
						} else if (index === 1) {
							uni.chooseImage({
								count: 1, //默认9
								sizeType: ['original', 'compressed'], //可以指定是原图还是压缩图，默认二者都有
								sourceType: ['album'], //从相册选择
								success: function(res) {
									uni.showLoading({
										title: '上传中...',
										icon: 'loading',
										duration: 2000
									});

									// TODO 是否要判断令牌和id等
									// let token = uni.getStorageSync('token');
									// let userId = uni.getStorageSync('userId');

									//上传图片到后台
									uni.uploadFile({
										url: "http://localhost:8080/upload",
										filePath: res.tempFilePaths[0],
										name: "file",
										success: (r => {
											console.log(r);
											// 需要转成json格式，否则拿不到返回的图片地址
											let result = JSON.parse(r.data);

											console.log(result.data);

											that.user.avr = result.data;
											console.log(that)


											//修改用户的头像

											uni.showToast({
												title: "上传成功",
												icon: "none",
											});
										})
									});
								}
							});
						}
					}
				})
			},
			config: function(name) {
				var info = null;
				if (name) {
					var name2 = name.split("."); //字符分割
					if (name2.length > 1) {
						info = configdata[name2[0]][name2[1]] || null;
					} else {
						info = configdata[name] || null;
					}
					if (info == null) {
						let web_config = cache.get("web_config");
						if (web_config) {
							if (name2.length > 1) {
								info = web_config[name2[0]][name2[1]] || null;
							} else {
								info = web_config[name] || null;
							}
						}
					}
				}
				return info;
			},
			getUserInfo() {
				let userId = this.$queue.getData('userId');
				this.$Request.getT('/user/find?id=' + userId).then(res => {
					if (res.status === 0) {
						this.userName = res.data.userName;
						this.phone = res.data.phone;
						this.headImg = res.data.headImg;
						this.realName = res.data.realName;
						this.nickName = res.data.nickName;
						this.userId = res.data.userId;
						this.password = res.data.password;
						this.createTime = res.data.createTime;
						this.money = res.data.money;
						this.platform = res.data.platform;
						console.log(this.platform)
						this.jiFen = res.data.jiFen;
						this.weChatId = res.data.weChatId;
						this.status = res.data.status;
						this.zhiFuBao = res.data.zhiFuBao;
						this.zhiFuBaoName = res.data.zhiFuBaoName;
					} else {
						uni.showModal({
							showCancel: false,
							title: '未知错误',
							content: res.msg
						});
						this.$queue.logout();
					}
					uni.hideLoading();
				});
			},
			// 保存
			messagebtn() {
				this.user.userImages = this.formData.imgSrc;
				console.log(this.user);
				//TODO 是否需要对个人用户的信息进行非空校验，暂时不设置
				if (this.user.nick == "") {
					return uni.showToast({
						title: "昵称不能为空",
						icon: "none"
					})
				};
				uni.showModal({
					title: '温馨提示',
					content: '确定保存信息',
					success: e => {
						if (e.confirm) {
							this.$myRequest({
								url: "/user/updateBase",
								method: "post",
								data: this.user
							}).then(r => {
								console.log(r);
								console.log(this.user);
								if (r.data.code == "200") {
									uni.showToast({
										title: '保存成功！',
										//将值设置为 success 或者直接不用写icon这个参数
										icon: 'success',
										//显示持续时间为 2秒
										duration: 2000
									})
									setTimeout(() => {
										this.$router.go(0)
									}, 400)
								} else {
									uni.showToast({
										title: "系统繁忙",
										//将值设置为 success 或者直接不用写icon这个参数
										icon: 'fail',
										//显示持续时间为 2秒
										duration: 2000
									})
								};
							})
						}
					}
				});

			},
			userphone() {
				uni.navigateTo({
					url: '/pages/my/userphone'
				})
			},
			imgPreview(index) {
				console.log("查看大图")
				uni.previewImage({
					urls: this.urls,
					current: index, // 当前显示图片的http链接，默认是第一个
				})
			},
			selectFile(e) {
				// console.log(e.tempFilePaths[0]);
				// console.log("选择文件");
				uni.uploadFile({
					url: "http://localhost:8080/upload",
					filePath: e.tempFilePaths[0],
					name: "file",
					success: (r => {
						// 转成json格式
						let result = JSON.parse(r.data);
						//console.log(result);
						this.formData.imgSrc.push(result.data);
						this.urlMap.url = e.tempFilePaths[0];
						this.urlMap.realurl = result.data;
						this.urlMapping.push(this.urlMap);
						console.log(this.formData.imgSrc);
						uni.showToast({
							title: "上传成功",
							icon: "none",
						});
					})
				});
			},
			deleteFile(e) {
				let toDelUrl = "";
				// 根绝虚拟url删除真实url
				for (let urlMap of this.urlMapping) {
					if (urlMap.url == e.tempFilePath) {
						toDelUrl = urlMap.url;
						this.formData.imgSrc.splice(this.formData.imgSrc.indexOf(toDelUrl), 1)
						break;
					}
				}
				//console.log(this.formData.imgSrc);
				uni.showToast({
					title: "删除成功",
					icon: "none",
				});
			},
		}
	};
</script>

<style>
	/* page {
		background: #1c1b20;
	} */
	.usermain {
		background: #111224;
	}

	.usermain-item {
		display: flex;
		align-items: center;
		margin-left: 40rpx;
		padding: 30rpx 40rpx 30rpx 0;
		justify-content: space-between;
		/* border-bottom: 2rpx solid #f2f2f2; */
	}

	.usermain-item.item-padding {
		padding: 0 40rpx 0 0;
	}

	.cu-form-group {
		padding: 0;
		background: #111224;
		text-align: right;
	}

	.cu-form-group input {
		background: #111224;
		font-size: 28rpx;
		color: #333333;

	}

	.footer-btn {
		margin-top: 150rpx;
	}

	.footer-btn .usermain-btn {
		color: #ffffff;
		background: #5E81F9;
		text-align: center;
		width: 450rpx;
		height: 80rpx;
		font-size: 28rpx;
		line-height: 80rpx;
		margin: 0 auto;
		border-radius: 40rpx;
	}
</style>
